<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="iconfont navbar-icon">&#xe65d;</text>
      </view>
      <text class="navbar-title">编辑资料</text>
      <view class="navbar-right" @click="handleSave">
        <text class="save-text" :class="{ disabled: loading }">
          {{ loading ? '保存中...' : '保存' }}
        </text>
      </view>
    </view>

    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="changeAvatar">
        <image 
          class="avatar-img" 
          :src="formData.avatar || defaultAvatar"
          mode="aspectFill"
          @error="handleAvatarError"
        />
        <view class="avatar-overlay">
          <text class="iconfont avatar-camera">&#xe613;</text>
          <text class="avatar-text">更换头像</text>
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 用户名 -->
      <view class="form-group">
        <text class="form-label">用户名</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.userName" 
            placeholder="请输入用户名"
            maxlength="20"
            @blur="validateUserName"
          />
        </view>
        <text v-if="errors.userName" class="error-text">{{ errors.userName }}</text>
      </view>

      <!-- 手机号 -->
      <view class="form-group">
        <text class="form-label">手机号</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
            @blur="validatePhone"
          />
        </view>
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
      </view>

      <!-- 邮箱 -->
      <view class="form-group">
        <text class="form-label">邮箱</text>
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.email" 
            placeholder="请输入邮箱（可选）"
            @blur="validateEmail"
          />
        </view>
        <text v-if="errors.email" class="error-text">{{ errors.email }}</text>
      </view>

      <!-- 性别 -->
      <view class="form-group">
        <text class="form-label">性别</text>
        <view class="form-item">
          <radio-group class="gender-group" @change="onGenderChange">
            <label class="gender-item">
              <radio 
                value="0" 
                :checked="formData.gender === 0"
                color="#667eea"
              />
              <text class="gender-text">未知</text>
            </label>
            <label class="gender-item">
              <radio 
                value="1" 
                :checked="formData.gender === 1"
                color="#667eea"
              />
              <text class="gender-text">男</text>
            </label>
            <label class="gender-item">
              <radio 
                value="2" 
                :checked="formData.gender === 2"
                color="#667eea"
              />
              <text class="gender-text">女</text>
            </label>
          </radio-group>
        </view>
      </view>

      <!-- 生日 -->
      <view class="form-group">
        <text class="form-label">生日</text>
        <picker 
          mode="date" 
          :value="formData.birthday || '1990-01-01'"
          start="1900-01-01"
          :end="currentDate"
          @change="onDateChange"
        >
          <view class="form-item form-picker">
            <text class="picker-text" :class="{ placeholder: !formData.birthday }">
              {{ formData.birthday || '请选择生日' }}
            </text>
            <text class="iconfont picker-arrow">&#xe65f;</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 其他功能区域 -->
    <view class="action-section">
      <view class="action-item" @click="changePassword">
        <text class="action-icon">🔒</text>
        <text class="action-text">修改密码</text>
        <text class="iconfont action-arrow">&#xe65f;</text>
      </view>
    </view>

    <!-- 日期选择器（移除多余的选择器） -->
  </view>
</template>

<script>
import { request } from '@/utils/request.js';
import { uploadFile } from '@/utils/upload.js';
import { getUserInfo, setUserInfo, fetchUserProfile } from '@/utils/auth.js';

export default {
  data() {
    return {
      loading: false,
      defaultAvatar: 'https://picsum.photos/120/120?random=20',
      currentDate: '',
      
      // 表单数据
      formData: {
        id: '',
        userName: '',
        phone: '',
        email: '',
        gender: 0,
        birthday: '',
        avatar: ''
      },
      
      // 原始数据（用于对比是否有修改）
      originalData: {},
      
      // 验证错误
      errors: {
        userName: '',
        phone: '',
        email: ''
      }
    }
  },
  
  onLoad() {
    this.initCurrentDate();
    this.loadUserData();
  },
  
  methods: {
    // 初始化当前日期
    initCurrentDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = (today.getMonth() + 1).toString().padStart(2, '0');
      const day = today.getDate().toString().padStart(2, '0');
      this.currentDate = `${year}-${month}-${day}`;
    },
    
    // 加载用户数据
    async loadUserData() {
      try {
        const userInfo = getUserInfo();
        if (!userInfo || !userInfo.id) {
          uni.showToast({
            title: '用户信息获取失败',
            icon: 'error'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
          return;
        }
        
        // 先使用本地用户信息初始化
        this.formData = {
          id: userInfo.id,
          userName: userInfo.userName || userInfo.username || '',
          phone: userInfo.phone || '',
          email: userInfo.email || '',
          gender: userInfo.gender || 0,
          birthday: this.formatDate(userInfo.birthday),
          avatar: userInfo.avatar || ''
        };
        
        // 保存原始数据
        this.originalData = JSON.parse(JSON.stringify(this.formData));
        
        // 尝试获取最新用户信息
        try {
          const latestUserInfo = await fetchUserProfile();
          if (latestUserInfo) {
            this.formData = {
              id: latestUserInfo.id,
              userName: latestUserInfo.userName || latestUserInfo.username || '',
              phone: latestUserInfo.phone || '',
              email: latestUserInfo.email || '',
              gender: latestUserInfo.gender || 0,
              birthday: this.formatDate(latestUserInfo.birthday),
              avatar: latestUserInfo.avatar || ''
            };
            
            // 更新原始数据
            this.originalData = JSON.parse(JSON.stringify(this.formData));
          }
        } catch (profileError) {
          console.log('获取最新用户信息失败，使用本地缓存:', profileError);
          // 继续使用本地信息，不影响用户体验
        }
        
      } catch (error) {
        console.error('加载用户数据失败:', error);
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'error'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 验证用户名
    validateUserName() {
      const userName = this.formData.userName.trim();
      if (!userName) {
        this.errors.userName = '请输入用户名';
        return false;
      }
      if (userName.length < 2) {
        this.errors.userName = '用户名至少2个字符';
        return false;
      }
      if (userName.length > 20) {
        this.errors.userName = '用户名不能超过20个字符';
        return false;
      }
      this.errors.userName = '';
      return true;
    },
    
    // 验证手机号
    validatePhone() {
      const phone = this.formData.phone.trim();
      if (!phone) {
        this.errors.phone = '请输入手机号';
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        this.errors.phone = '请输入有效的手机号';
        return false;
      }
      this.errors.phone = '';
      return true;
    },
    
    // 验证邮箱
    validateEmail() {
      const email = this.formData.email.trim();
      if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        this.errors.email = '请输入有效的邮箱地址';
        return false;
      }
      this.errors.email = '';
      return true;
    },
    
    // 验证所有字段
    validateAllFields() {
      const isUserNameValid = this.validateUserName();
      const isPhoneValid = this.validatePhone();
      const isEmailValid = this.validateEmail();
      
      return isUserNameValid && isPhoneValid && isEmailValid;
    },
    
    // 性别选择变化
    onGenderChange(e) {
      this.formData.gender = parseInt(e.detail.value);
    },
    
    // 日期选择变化
    onDateChange(e) {
      this.formData.birthday = e.detail.value;
    },
    
    // 更换头像
    changeAvatar() {
      uni.showActionSheet({
        itemList: ['拍照', '从相册选择'],
        success: (res) => {
          const sourceType = res.tapIndex === 0 ? 'camera' : 'album';
          this.chooseImage(sourceType);
        }
      });
    },
    
    // 选择图片
    chooseImage(sourceType) {
      uni.chooseImage({
        count: 1,
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 显示加载提示
          uni.showLoading({
            title: '上传中...'
          });
          
          try {
            // 上传图片
            const uploadResult = await uploadFile(tempFilePath, 'avatar');
            
            if (uploadResult && uploadResult.url) {
              this.formData.avatar = uploadResult.url;
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              });
            } else {
              throw new Error('上传失败');
            }
            
          } catch (error) {
            console.error('头像上传失败:', error);
            uni.showToast({
              title: '头像上传失败',
              icon: 'error'
            });
          } finally {
            uni.hideLoading();
          }
        }
      });
    },
    
    // 头像加载失败处理
    handleAvatarError() {
      console.log('头像加载失败，使用默认头像');
    },
    
    // 修改密码
    changePassword() {
      uni.navigateTo({
        url: '/pages/profile/password'
      });
    },
    
    // 检查数据是否有变化
    hasDataChanged() {
      try {
        return JSON.stringify(this.formData) !== JSON.stringify(this.originalData);
      } catch (error) {
        console.error('检查数据变化失败:', error);
        return false; // 出错时假设无变化，允许用户离开
      }
    },
    
    // 保存用户信息
    async handleSave() {
      if (this.loading) return;
      
      // 验证表单
      if (!this.validateAllFields()) {
        uni.showToast({
          title: '请检查输入信息',
          icon: 'error'
        });
        return;
      }
      
      // 检查是否有修改
      if (!this.hasDataChanged()) {
        uni.showToast({
          title: '没有修改',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      
      try {
        const updateData = {
          userName: this.formData.userName.trim(),
          phone: this.formData.phone.trim(),
          email: this.formData.email.trim() || null,
          gender: this.formData.gender,
          birthday: this.formData.birthday || null,
          avatar: this.formData.avatar || null
        };
        
        const response = await request({
          url: `/api/user/${this.formData.id}`,
          method: 'PUT',
          data: updateData
        });
        
        if (response.success) {
          // 更新本地用户信息
          const updatedUserInfo = { ...getUserInfo(), ...updateData };
          await setUserInfo(updatedUserInfo);
          
          // 重要：更新原始数据，标记为已保存状态
          this.originalData = JSON.parse(JSON.stringify(this.formData));
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack({
              fail: () => {
                // 如果navigateBack失败，尝试跳转到用户页面
                uni.switchTab({
                  url: '/pages/user/index'
                });
              }
            });
          }, 1500);
          
        } else {
          uni.showToast({
            title: response.message || '保存失败',
            icon: 'error'
          });
        }
        
      } catch (error) {
        console.error('保存用户信息失败:', error);
        uni.showToast({
          title: error?.message?.includes('网络') ? '网络错误，请重试' : '保存失败，请重试',
          icon: 'error'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 返回上一页
    goBack() {
    
        
          this.forceGoBack();

    },
    
    // 强制返回上一页
    forceGoBack() {
      try {
        uni.navigateBack({
          fail: () => {
            // 如果navigateBack失败，跳转到用户页面
            uni.switchTab({
              url: '/pages/user/index',
              fail: () => {
                // 最后的备选方案：重新加载页面
                uni.reLaunch({
                  url: '/pages/user/index'
                });
              }
            });
          }
        });
      } catch (error) {
        console.error('强制返回失败:', error);
        // 最后的备选方案
        uni.reLaunch({
          url: '/pages/user/index'
        });
      }
    }
  }
}
</script>

<style scoped>
/* 基本样式 */
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 自定义导航栏 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-left,
.navbar-right {
  width: 60px;
}

.navbar-icon {
  font-size: 20px;
  color: #333;
}

.navbar-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.save-text {
  color: #667eea;
  font-size: 16px;
  text-align: right;
}

.save-text.disabled {
  color: #ccc;
}

/* 头像区域 */
.avatar-section {
  background: #fff;
  padding: 40px 0 30px;
  text-align: center;
  margin-top: 60px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: #fff;
}

.avatar-container:active .avatar-overlay {
  opacity: 1;
}

.avatar-camera {
  font-size: 24px;
  margin-bottom: 4px;
}

.avatar-text {
  font-size: 12px;
}

/* 表单区域 */
.form-section {
  margin-top: 16px;
}

.form-group {
  background: #fff;
  margin-bottom: 16px;
  padding: 0 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #666;
  padding: 16px 0 8px;
}

.form-item {
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.form-input {
  width: 100%;
  font-size: 16px;
  color: #333;
  padding: 8px 0;
}

.form-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  cursor: pointer;
}

.picker-text {
  font-size: 16px;
  color: #333;
}

.picker-text.placeholder {
  color: #999;
}

.picker-arrow {
  font-size: 14px;
  color: #ccc;
}

/* 性别选择 */
.gender-group {
  display: flex;
  gap: 24px;
}

.gender-item {
  display: flex;
  align-items: center;
}

.gender-text {
  margin-left: 8px;
  font-size: 16px;
  color: #333;
}

/* 错误提示 */
.error-text {
  color: #ff4757;
  font-size: 12px;
  margin-top: 4px;
  margin-left: 16px;
}

/* 操作区域 */
.action-section {
  margin-top: 16px;
  background: #fff;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.3s;
}

.action-item:active {
  background: #f8f8f8;
}

.action-item:last-child {
  border-bottom: none;
}

.action-icon {
  font-size: 18px;
  margin-right: 12px;
}

.action-text {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.action-arrow {
  font-size: 14px;
  color: #ccc;
}
</style>